import { getToken, setToken } from "@/utils/token";
import {
    SET_TOKEN,
    setTokenActionCreator,
    UserAction,
    setUserInfoActionCreator,
} from "@/redux/user/userReducerAction";
import { ThunkAction } from "redux-thunk";
import { RootState } from "@/redux";
import { User } from "@/types";
import { getUserInfo } from "@/api";
import { SET_USER_INFO } from "./userReducerAction";

interface UserState {
    token: string | null;
    userInfo: User | null;
}
const defaultState: UserState = {
    token: getToken(),
    userInfo: null,
};
export default (state = defaultState, action: UserAction) => {
    switch (action.type) {
        case SET_TOKEN:
            return { ...state, token: action.payload };
        case SET_USER_INFO:
            return { ...state, userInfo: action.payload };
        default:
            return state;
    }
};
export const setTokenAction =
    (token: string): ThunkAction<any, RootState, unknown, UserAction> =>
    dispatch => {
        setToken(token);
        dispatch(setTokenActionCreator(token));
    };

export const getUserAction =
    (): ThunkAction<any, RootState, unknown, UserAction> => async dispatch => {
        const res = await getUserInfo();
        dispatch(setUserInfoActionCreator(res.data));
    };
